package com.x2.modular.system.tag;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.x2.modular.system.entity.Dict;
import com.x2.modular.system.entity.DictType;

import java.io.IOException;
import java.util.List;

public class SysDicCheckBoxTag extends SysDicBaseTag {

    @Override
    public void render() {
        initAttr();
        StringBuilder sb = new StringBuilder();
        if (StringUtils.checkValNotNull(dicCode)) {
            QueryWrapper<DictType> dictTypeQueryWrapper = new QueryWrapper<>();
            dictTypeQueryWrapper.eq("code", dicCode);
            DictType dictType = dictTypeService.getOne(dictTypeQueryWrapper);
            if (dictType != null) {
                QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
                dictQueryWrapper.eq("dict_type_id", dictType.getDictTypeId());
                dictQueryWrapper.orderByAsc("sort");
                List<Dict> lst = dictService.list(dictQueryWrapper);
                String paramValue = this.getDefaultValue();
                int index = 0;
                for (Dict option : lst) {
                    String id = this.getType() + "_" + this.getName() + "_" + option.getCode();
                    sb.append(" <input type='checkbox'  id='").append(id).append("' ");
                    if (this.getName() != null && this.getName().trim().length() > 0) {
                        sb.append(" name='" + this.getName().trim() + "' ");
                    }
                    sb.append(" title='").append(option.getName()).append("'");
                    sb.append(" value='").append(option.getCode()).append("'");
                    if (this.getSkin() != null) {
                        sb.append(" lay-skin='").append(this.getSkin()).append("'");
                    }
                    if (this.getOnChange() != null) {
                        sb.append(" lay-filter='").append(this.getOnChange()).append("'");
                    }
                    if (this.getLayVerify() != null) {
                        sb.append(" lay-verify='").append(this.getLayVerify()).append("'");
                    }
                    //注释掉默认选中第一个，我也不知道当时怎么想的这么写
                  /*  if(index == 0) {
                        sb.append(" checked ");
                    }*/
                    if (paramValue != null && paramValue.equals(option.getCode())) {
                        sb.append(" checked ");
                    }
                    sb.append(" /> ");
                    index++;
                }
            }
        }
        try {
            this.ctx.byteWriter.writeString(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
